package org.young.admin.common;

import org.apache.shiro.authc.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.young.common.bean.Result;
import org.young.common.enums.CommonEnum;
import org.young.common.exception.BizException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author young 2021年5月10日
 */
@SuppressWarnings("all")
@ControllerAdvice
public class GlobalExceptionHandler {

	private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	/**
	 * 处理自定义的业务异常
	 *
	 * @param req
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = BizException.class)
	@ResponseBody
	public Result bizExceptionHandler(HttpServletRequest req, BizException e) {
		logger.error("发生业务异常！原因是：{}", e.getErrorMsg());
		return Result.error(e.getErrorCode(), e.getErrorMsg());
	}

	/**
	 * 处理shiro框架异常
	 *
	 * @param e
	 * @return
	 */
	@ExceptionHandler(AuthenticationException.class)
	public Result<?> doHandleAuthenticationException(AuthenticationException e) {
		logger.error("认证异常！原因是:", e);
		return Result.error(HttpStatus.UNAUTHORIZED.toString(), e.getMessage());
	}

	/**
	 * 处理其他异常
	 *
	 * @param req
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public Result exceptionHandler(HttpServletRequest req, Exception e) {
		logger.error("未知异常！原因是:", e);
		return Result.error(CommonEnum.INTERNAL_SERVER_ERROR);
	}
}
